package com.qf.listener;

import com.qf.constatns.RabbitMQConstatns;
import com.qf.entity.OrderEntity;
import com.qf.service.OrderService;
import com.qf.utils.ExecutorUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Slf4j
public class OrderDlxListener {

    @Autowired
    private OrderService orderService;

    private ThreadPoolExecutor exceptions = ExecutorUtils.getExcutorsPool();

    @RabbitListener(queues = RabbitMQConstatns.ORDER_DLX_QUEUE)
    public void orderStatus(OrderEntity orderEntity, Channel channel, Message message) {
        exceptions.submit(()->{
            log.debug("订单已经到了超时时间，此时应该去判断订单是否还是未支付的状态:" + orderEntity);
            // 1.查询最新的订单状态
            OrderEntity newOrder = orderService.getOrderById2(orderEntity.getOid());

            // 2.判断订单状态
            switch (newOrder.getStatus()) {
                case 1: // 未支付
                    log.debug("已经1m了，还是未支付状态，此时更新订单状态为已超时了");
                    orderService.updateOrderStatus(newOrder.getOid(), 4);
                    // 释放库存？？？
                    break;
                case 2: // 已支付
                    log.debug("已经1m了，订单已经支付成功了，不需要做处理");
                    break;
                case 3: // 已取消
                    log.debug("订单已取消");
            }

            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });


    }
}
